#pragma once
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <cassert>
#include <unordered_map>
#include <ctype.h>
#include <pthread.h>
#include "Log.hpp"

using namespace std;

class Sock
{
public:
    const static int gbacklog = 10; // 全连接队列

    Sock() {}
    ~Sock() {}
    static int Socket()
    {
        // 1.创建套接字
        int listen_sock = socket(AF_INET, SOCK_STREAM, 0); // 基于tcp有连接可靠流式传输
        if (listen_sock < 0)
        {
            logMessage(FATAL, "创建socket失败:%s\n", strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "create socket success, sock:%d\n", listen_sock);
        return listen_sock;
    }
    static void Bind(int listen_sock, uint16_t port = 8080, const string ip = "0.0.0.0")
    {
        // 2.绑定ip和port
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = inet_addr(ip.c_str());
        local.sin_port = htons(port);

        if (bind(listen_sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "绑定socket失败:%s\n", strerror(errno));
            exit(3);
        }
    }
    static void Listen(int listen_sock)
    {
        // 3.监听
        if (listen(listen_sock, gbacklog) < 0)
        {
            logMessage(FATAL, "监听socket失败:%s\n", strerror(errno));
            exit(4);
        }

        logMessage(WARNING, "初始化udp服务器成功,sock:%d", listen_sock);
    }
    static int Accept(int listen_sock, string *cli_ip, uint16_t *cli_port) //*输出型参数，&输入型参数
    {
        assert(cli_ip && cli_port);
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int server_sock = accept(listen_sock, (struct sockaddr *)&client, &len);
        if (server_sock < 0)
        {
            logMessage(ERROR, "accept 获取连接失败");
        }
        *cli_ip = inet_ntoa(client.sin_addr);
        *cli_port = ntohs(client.sin_port);
        return server_sock;
    }
    static bool Connect(int sock, const string &srv_ip, uint16_t srv_port)
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(srv_ip.c_str());
        server.sin_port = srv_port;
        if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) // 建立连接
        {
            cerr << "connect server error" << endl;
            exit(2);
        } // 可以设置重连策略：连接n次都连不上服务器，就退出客户端
        cout << "connect server success" << endl;
    }
};